# CCN::Scripting.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information visit http://carrierclass.net/
#
use strict; use warnings;

package CCN::Scripting;
use CCN::Class;

sub run_command
{
    if($_[0] =~ /^!/ )
    {
        my $cmd = join(' ',@_);
        eval_command(substr($cmd,1));
    }
    else
    {
        exec_command(@_);
    }
}

sub eval_command
{
    my $cmd = join(' ',@_);
    eval $cmd;
    return if not $@;

    my $d = new CCN::Class;
    $d->die("run_eval: Failed to execute $cmd: $@");
}

sub exec_command
{
    $ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
    system @_;
    return if $? == 0;

    my $cmd = join(' ',@_);
    
    my $d = new CCN::Class;
    $d->die ("run_shell: Failed to execute $cmd: $!"        )  if $? == -1;
    $d->die ("run_shell: $cmd failed with signal ".($?&127) )  if $? & 127;
    $d->die ("run_shell: $cmd returned ".($?>>8)            )  if ($?>>8) != 0;
    $d->die ("run_shell: failed $cmd");
}

1;